package com.lzw.mall.order.controller;

import com.lzw.mall.common.service.IMemberService;
import com.lzw.mall.common.util.StringUtil;
import com.lzw.mall.common.vo.ResultVO;
import com.lzw.mall.order.util.SendMsgUtil;
import com.ramostear.captcha.HappyCaptcha;
import com.ramostear.captcha.common.Fonts;
import com.ramostear.captcha.support.CaptchaStyle;
import com.ramostear.captcha.support.CaptchaType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/")
public class LoginController {

    @Autowired
    private IMemberService memberService;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @GetMapping("/login")
    public String login(){
        return "login";
    }

    @GetMapping("/register")
    public String register() {
        return "register";
    }

    @PostMapping("/login")
    public String doLogin(String username,String password,String code,HttpServletRequest request) {
        boolean b=memberService.check(username,password,code,request);
        if (b) {
            return "redirect:/";
        }else {
            return "login";
        }
    }

    @GetMapping("/msgCode")
    @ResponseBody
    public void sendMsg(String tel) throws Exception {
        String code = StringUtil.generateRandomCode(6,0);
        redisTemplate.opsForValue().set("reg-code-"+tel,code,5, TimeUnit.MINUTES);
        SendMsgUtil.sendMsg(tel, code);
    }

    @GetMapping("/captcha")
    @ResponseBody
    public void captcha(HttpServletRequest req,HttpServletResponse res){
        HappyCaptcha.require(req,res)
                .style(CaptchaStyle.ANIM)			//设置展现样式为动画
                /*.type(CaptchaType.CHINESE)			//设置验证码内容为汉字*/
                .length(6)							//设置字符长度为6
               /* .width(220)							//设置动画宽度为220*/
                .height(42)							//设置动画高度为80
               /* .font(Fonts.getInstance().zhFont())	//设置汉字的字体*/
                .build().finish();      			//生成并输出验证码
    }

    @GetMapping("/selectByUsername")
    @ResponseBody
    public ResultVO doSelectByUsername(){
        return memberService.doSelectByUsername();
    }

}
